/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.sqlite;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.sqlite.SQLiteConfig;

/**
 *
 * @author Administrator
 */
public class SqliteUtil {
    private static final Logger logger = Logger.getLogger(SqliteUtil.class.getName());
    private static final String connectionStr = "jdbc:sqlite:data/sample.db";
    private static final String driverClassName = "org.sqlite.JDBC";
    private static  Connection connection;
    private static  Statement statement;
    
    static {
        try {
            // load the sqlite-JDBC driver using the current class loader
            Class.forName(driverClassName);
        } catch (ClassNotFoundException ex) {
            logger.log(Level.SEVERE, "无法找到sqlite-JDBC驱动", ex);
        }
        SQLiteConfig config = new SQLiteConfig();
        //config.setEncoding(SQLiteConfig.Encoding.UTF8);//why error?
        try {
            connection = DriverManager.getConnection(connectionStr, config.toProperties());

        }
        catch (SQLException ex) {
            logger.log(Level.SEVERE, "无法创建数据库连接对象", ex);
        }
        try {
            statement = connection.createStatement();
            statement.setQueryTimeout(30);  // set timeout to 30 sec.
        }
        catch (SQLException ex) {
            logger.log(Level.SEVERE, "无法创建数据库连接对象", ex);
        }
       
    }
    
    /**
     * 数据备份到文件
     * @param dataBaseFile 相对于项目根目录
     */
    public static void backupTo(String dataBaseFile){
        try {
            statement.executeUpdate("backup to "+dataBaseFile);
        }
        catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * 从数据文件恢复
     * @param dataBaseFile 相对于项目根目录
     */
    public static void restoreFrom(String dataBaseFile){
        try {
            statement.executeUpdate("restore from "+dataBaseFile);
        }
        catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
    
    public static void main(String arge[]){
        backupTo("data/back.db");
        restoreFrom("data/back.db");
    }
    
}
